<template>
    <div>
        <div flex style="height: 100%;">
            <base-layout :defaultButtonSwitch="false" :buttonShow="false" style="width:260px;" :isPage="false"
                :showTitle="false" :buttonList="buttonTreeList" @onFuncBtn="handleTreeThings">
                <div slot="main" style="height: 100%;overflow-y: auto;border-right: 1px solid #dfe6ec;">
                    <base-tree :isCenter="false" :isSaveBtn="false" :Allshow="false" :showCheckbox="false"
                        :menuData="menuData" @handleNodeClick="orangClick"></base-tree>
                </div>
            </base-layout>
            <base-layout :buttonList="buttonList" :isPage="true" @onFuncBtn="handleDialog" style="flex:1;"
                :showTitle="false" ref="inventoryTablePage" @pageChange="onPageChange">
                <div slot="main" slot-scope="{ tableHeight }" style="height: 100%;">
                    <base-table :border="true" :showIndex="false" :slotrow="true" :tableHeight="tableHeight"
                        @onFunc="onFunc" :funData="funData" :tabLoading.sync="tabLoading" :tableData="tableData"
                        :tableColumn="tableColumn" @radioChange="getSelectTableData" ref="tableData">
                        <template v-slot:option="{ row }">
                            <el-radio v-model="radioInventory" :label="row.$index"></el-radio>
                        </template>
                        <template v-slot:companyCount="{ row }">
                            <span @click="handleclickOpenChecklist(row.row)"
                                style="width:100%;cursor: pointer;color:#3ca2e1">{{
                                    row.row.companyCount
                                }}</span>
                        </template>
                    </base-table>
                </div>
            </base-layout>
        </div>
        <!-- S 新增弹窗 -->
        <base-dialog :dialogVisible.sync="fileManagementDialog" :closeModal="false" :footerShow="true" :title="dialogType"
            width="55%" top="20vh" @handleConfirmClick="handleAddDialogDetails">
            <base-form :formRow="supplierFormList" :rules="rules" :isFunBtn="isFunBtn" ref="supplierForm"></base-form>
        </base-dialog>
        <!-- E 新增弹窗 -->


        <!-- S 组织机构树弹窗 -->
        <base-dialog :dialogVisible.sync="treeManagementDialog" :closeModal="false" :footerShow="true"
            :title="treeDialogType" width="55%" top="20vh" @handleConfirmClick="handleTreeDialogDetails">
            <base-form :formRow="treeDialogListRow" :isFunBtn="isFunBtn" :rules="treeDialogRules"
                ref="treeDataRef"></base-form>
        </base-dialog>
        <!-- E 组织机构树弹窗 -->


        <!-- S 查看 -->
        <base-dialog :dialogVisible.sync="showManagementDialog" :closeModal="false" :footerShow="true" title="查看"
            width="55%" top="20vh" @handleConfirmClick="handleShowDialogDetails">
            <look-form :formRow="showFormColumn" :spanNumber="spanNumber" :ruleForm="showFormData"></look-form>
        </base-dialog>
        <!-- E 查看 -->

        <!-- S 选择所属公司弹窗 -->
        <base-dialog :dialogVisible.sync="showOperateDialog" :closeModal="false" :footerShow="true" title="选择所属公司"
            width="45%" height="75vh" top="20vh" @handleConfirmClick="handleOperateDialogDetails">
            <el-checkbox-group v-model="checkList" style="display: flex;flex-wrap: wrap;">
                <el-checkbox v-for="(item, index) in labelList" :key="index" style="width: 28%;padding: 10px;" :label="item.companyName
                    " :checked="item.checked"></el-checkbox>
            </el-checkbox-group>
        </base-dialog>
        <!-- E 选择所属公司弹窗 -->

        <!-- S 所属公司查看弹窗 -->
        <base-dialog :dialogVisible.sync="showCompanyDialog" :closeModal="false" :footerShow="false" title="所属公司"
            height="75vh" width="15%" top="20vh">
            <div class="company-list" v-for="(item, index) in openList" :key="index">{{ item.companyName }}</div>
        </base-dialog>
        <!-- E 所属公司查看弹窗 -->

    </div>
</template>

<script>
// 组件
import baseLayout from '@/components/base/baseLayout'
import baseTable from '@/components/base/baseTable'
import baseDialog from '@/components/base/BaseNewDialog'
import baseForm from '@/components/base/baseNewForm'
import baseTree from '@/components/base/BaseMenuTree'
import lookForm from '@/components/base/baselookForm'

// 表头数据
import configData from './configData'
// 表格数据
import {
    inventoryGetBillList, //存货档案列表表格
    GetInvBillList, //组织列表
    inventoryGetBillEditList, //存货档案详情信息
    inventorySaveData, //供应商保存
    inventoryDelData,
    classifySaveInvData,
    classifyDelInvData,
    GetInvEditList,
    dataDictionaryGetBillData, //存货档案计量单位下拉框
    SaveVenDate, GetDistribute
} from '@/api/apis/fileManagement'
import {
    OrganGetCompany
} from '@/api/apis/organization'
export default {
    name: 'inventoryManagement',
    components: {
        baseLayout,
        baseTable,
        baseDialog,
        baseForm,
        baseTree,
        lookForm,
    },
    data() {
        return {
            mainColor: '#f8f8f8',
            menuData: [], //菜单树数据
            funData: [{
                color: '#3CA2E1',
                text: '选择所属公司'
            },
            ],
            buttonList: [
                {
                    icon: 'el-icon-reading',
                    menuName: '查看',
                },
            ],
             //按钮组
            buttonTreeList: [
                {
                    icon: 'el-icon-plus',
                },
                {
                    icon: 'el-icon-edit',
                },
                {
                    icon: 'el-icon-delete',
                    type: 'danger',
                },
            ],
            //树
            treeManagementDialog: false,
            treeDialogType: '新增',
            tabLoading: false,
            // tableHeight: '67vh',
            tableData: [], //表格数据
            dialogType: '新增', //表格类型
            fileManagementDialog: false, //控制新增编辑弹窗是否打开
            Ddk_DataDicKindID: '', //组织
            selectTableData: [], //当前选中的数据
            treeDialogRules: configData.treeDialogRules,
            rules: configData.rules,

            supplierFormList: configData.inventoryFormList, //新增表单
            isFunBtn: false,
            treeNodeSelected: {
                //当前选中的树节点
                invClassify: '',
                invClassifyName: '',
            },

            selectTableData: {}, //当前选中的数据
            radioInventory: false,
            showManagementDialog: false, //查看
            showFormColumn: configData.showFormColumn,
            spanNumber: 8,
            showFormData: {},
            pageModel: {//分页
                limit: 20,
                page: 1
            },
            CreatePersonID: '',//创建人id
            showOperateDialog: false,//操作弹窗
            showCompanyDialog: false,//所属公司查看弹窗
            labelList: [],//
            checkList: [],
            openList: [],
        }
    },
    computed: {
        //供应商档案列表表头数据
        tableColumn() {
            return configData.inventoryTableColumn
        },
        treeDialogListRow() {
            return configData.treeFormData
        },
    },
    mounted() {
        // 初始化
        this.CreatePersonID = this.$store.state.user.info.UserID
        this.getMenuList()
        this.getTableData()
        this.dataDictionaryGetBillData()
        this.getCompanyList()

    },
    methods: {
        async handleclickOpenChecklist(row) {
            if (row.companyCount > 0) {
                this.getCheckListData(row)
                this.showCompanyDialog = true
            } else {
                this.getCheckListData(row)
            }
        },
        //操作
        onFunc(index, row) {
            // console.log(row);
            if (row.companyCount > 0) {
                this.getCheckListData(row)
            } else {
                this.checkList = []
            }
            this.showOperateDialog = true
        },
        // 存货档案表格数据
        async getTableData() {
            this.tabLoading = true
            let params = {
                ...this.pageModel,
                cusClassify: this.treeNodeSelected.invClassify, //当前点击分类id
                Sequence: '',
                SequenceName: '',
            }
            let res = await inventoryGetBillList(params)
            if (res.code == 1) {
                this.$nextTick(() => {
                    this.tableData = res.data[1]
                    this.$refs.tableData.clearRadioIndex()
                    this.selectTableData = {}
                    this.$refs.inventoryTablePage.setPageTotal(res.data[0])
                })
                this.tabLoading = false
            }
        },
        // 存货档案树
        async getMenuList() {
            let params = {}
            let res = await GetInvBillList(params)
            // 请求数据成功
            if (res.code === 1) {
                this.menuData = res.data[0]
            }
        },
        // 树节点被点击
        orangClick(data) {
            this.treeNodeSelected.invClassifyName = data.label
            this.treeNodeSelected.invClassify = data.id
            this.getTableData()
        },
        // 行单机
        getSelectTableData(val) {
            this.selectTableData = val
            this.radioInventory = val.index
        },
        // 分页
        onPageChange(model) {
            this.pageModel.page = model.page,
                this.pageModel.limit = model.limit
            this.getTableData()
        },
        // 计量单位
        async dataDictionaryGetBillData() {
            let param = {
                page: '1',
                limit: '20',
                KindId: '28',
                Sequence: 'descending',
                SequenceName: 'ddd_DicDetailsSort',
            }
            let res = await dataDictionaryGetBillData(param)
            if (res.code === 1) {
                let dataNew = []
                res.data[1].map(item => {
                    let _item = {
                        value: item.ddd_DicDetailsID,
                        label: item.ddd_DicDetailsName
                    }
                    dataNew.push(_item)
                })
                configData.inventoryFormList[1].elCol[1].options = dataNew
            }
        },
        // 获取当前行详情数据
        async getrowDetails(billid) {
            let params = {
                id: billid,
                op: "",
            }
            let res = await inventoryGetBillEditList(params)
            if (res.code === 1) {
                let data = res.data
                this.$nextTick(() => {
                    if (data[0].unit != '' && data[0].unit != null) {
                        data[0].unit = parseInt(data[0].unit)
                    }
                    // 编辑
                    if (this.fileManagementDialog === true) {
                        this.$refs.supplierForm.incomingParameters(data[0])
                    }
                    // 查看
                    if (this.showManagementDialog === true) {
                        this.showFormData = data[0]
                    }
                })
            }
        },
        // 按钮组
        handleDialog(item) {
            // 新增
            if (item.menuName === '新增') {
                this.dialogType = '新增'
                if (this.treeNodeSelected.invClassify === '') {
                    this.$vmNews('请选择分类', 'warning')
                    return
                } else {
                    this.fileManagementDialog = true
                    this.$nextTick(() => {
                        this.$refs.supplierForm.incomingParameters(this.treeNodeSelected)
                    })
                }
            }
            // 编辑
            if (item.menuName === '编辑') {
                this.dialogType = '编辑'
                if (Object.keys(this.selectTableData).length === 0) {
                    this.$vmNews('请选择一条数据!', 'warning')
                    return
                } else {
                    this.fileManagementDialog = true
                    this.$nextTick(() => {
                        let billid = this.selectTableData.billid
                        this.getrowDetails(billid)
                    })
                }
            }
            // 删除
            if (item.menuName === '删除') {
                if (Object.keys(this.selectTableData).length === 0) {
                    this.$vmNews('请选择一条数据!', 'warning')
                    return
                } else {
                    this.$delConfirm().then(() => {
                        let billid = this.selectTableData.billid
                        this.removeTableItem(billid)
                    })
                }
            }
            // 查看
            if (item.menuName === '查看') {
                if (Object.keys(this.selectTableData).length === 0) {
                    this.$vmNews('请选择一条数据!', 'warning')
                    return
                } else {
                    this.showManagementDialog = true
                    this.$nextTick(() => {
                        let billid = this.selectTableData.billid
                        this.getrowDetails(billid)
                    })
                }
            }
        },
        // 保存
        handleAddDialogDetails() {
            this.$refs.supplierForm.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    this.saveAddDialogDetails()
                }
            })
        },
        async saveAddDialogDetails() {
            let craeteUser = JSON.parse(localStorage.getItem('InfoData'))
            let params = {
                dataMain: {
                    billid:
                        this.dialogType === '新增'
                            ? '00000000-0000-0000-0000-000000000000'
                            : this.selectTableData.billid,
                    CreatePersonID: this.CreatePersonID,
                    ...this.$refs.supplierForm.ruleForm,
                },
            }
            let res = await inventorySaveData(params)
            if (res.code === 1) {
                this.$vmNews('保存成功', 'success')
                this.fileManagementDialog = false
                this.getTableData()
            }
        },
        // 删除
        async removeTableItem(billid) {
            let params = {
                id: billid,
            }
            let res = await inventoryDelData(params)
            if (res.code === 1) {
                this.$vmNews('删除成功！', 'success')
                this.getTableData()
            }
        },
        // 处理组织机构树事件
        handleTreeThings(item) {
            // 新增
            if (item.icon === 'el-icon-plus') {
                this.treeDialogType = '新增'
                if (this.treeNodeSelected.invClassify === '') {
                    this.$vmNews('请选择分类', 'warning')
                    return
                } else {
                    this.treeManagementDialog = true
                    let param = {
                        parentID: this.treeNodeSelected.invClassify,
                        codename: this.treeNodeSelected.invClassifyName,
                    }
                    this.$nextTick(() => {
                        this.$refs.treeDataRef.incomingParameters(param)
                    })
                }
            }
            // 编辑
            if (item.icon === 'el-icon-edit') {
                this.treeDialogType = '编辑'
                if (this.treeNodeSelected.invClassify === '') {
                    this.$vmNews('请选择分类', 'warning')
                    return
                } else {
                    this.treeManagementDialog = true
                    this.$nextTick(() => {
                        let id = this.treeNodeSelected.invClassify
                        this.getDetailsTreeNodeData(id)
                    })
                }
            }
            // 删除
            if (item.icon === 'el-icon-delete') {
                if (this.treeNodeSelected.invClassify === '') {
                    this.$vmNews('请选择分类', 'warning')
                    return
                } else {
                    this.$delConfirm().then(() => {
                        let id = this.treeNodeSelected.invClassify
                        this.deleteTreeDialogDetails(id)
                    })
                }
            }
        },
        // 选中节点的详细信息
        async getDetailsTreeNodeData(id) {
            let param = {
                id: id,
            }
            let res = await GetInvEditList(param)
            if (res.code === 1) {
                this.$refs.treeDataRef.incomingParameters(res.data[1])
            }
        },
        // 组织机构树提交保存
        handleTreeDialogDetails() {
            this.$refs.treeDataRef.$refs['ruleForm'].validate((valid) => {
                if (valid) { this.saveTreeDialogDetails() }
            })
        },
        async saveTreeDialogDetails() {
            let params = {
                dataMain: this.$refs.treeDataRef.ruleForm,
            }
            let res = await classifySaveInvData(params)
            if (res.code === 1) {
                this.$vmNews('保存成功', 'success')
                this.treeManagementDialog = false
                this.getMenuList()
                this.treeNodeSelected.invClassify = ''
                this.treeNodeSelected.invClassifyName = ''
            }
        },
        // 组织机构树删除
        async deleteTreeDialogDetails(id) {
            let param = {
                id: id,
            }
            let res = await classifyDelInvData(param)
            if (res.code === 1) {
                this.$vmNews('删除成功', 'success')
                this.getMenuList()
                this.treeNodeSelected.invClassify = ''
                this.treeNodeSelected.invClassifyName = ''
            }
        },
        // 查看弹窗 确认事件
        handleShowDialogDetails() {
            this.showManagementDialog = false
        },
        // 获取公司列表
        async getCompanyList() {
            let res = await OrganGetCompany({})
            if (res.code == 1) {
                this.labelList = res.data[0]
            }
        },
        //查询已分配公司列表
        async getCheckListData(row) {
            let params = {
                baseKind: row.invClassify, //客户种类
                baseID: row.billid //
            }
            let res = await GetDistribute(params)
            if (res.code == 1) {
                this.openList = res.data[0]
                this.checkList = this.openList.map(item => item.companyName)

            }

        },
        //选择所属公司弹窗确认
        async handleOperateDialogDetails() {
            //过滤并组成新数组
            const checkListId = this.labelList.filter(item => this.checkList.includes(item.companyName)).map(item => item.companyID);
            let params = {
                baseKind: this.selectTableData.invClassify,//客户分类id
                baseID: this.selectTableData.billid, //唯一billid
                companyID: checkListId
            }
            let res = await SaveVenDate(params)
            if (res.code === 1) {
                this.$vmNews('分配所属成功', 'success')
                this.showOperateDialog = false
                this.checkLis = []
                this.getTableData()
            }
        },
    },
    watch: {
        // 树弹窗
        treeManagementDialog: {
            deep: true,
            handler(newValue, oldValue) {
                if (newValue === false) {
                    // 重置表单
                    this.$refs.treeDataRef.resetFields('ruleForm')
                }
            },
        },
        // 新增编辑弹窗
        fileManagementDialog: {
            deep: true,
            handler(newValue, oldValue) {
                if (newValue === false) {
                    // 重置表单
                    this.$refs.supplierForm.resetFields('ruleForm')
                    this.$refs.inventoryTablePage.pageClear()
                }
            },
        },
    },
}
</script>

<style  scoped>
.organizationBody {
    display: flex;
    justify-content: space-evenly;
    background-color: #f2f3f4;
    padding: 10px;
}

::v-deep .el-form-item__error {
    padding: 0;
    top: 83%
}

>>>.el-radio__label {
    /* display: none; */
}

.company-list {
    display: flex;
    flex-direction: column;
    padding: 5px;
    align-items: center;
}
</style>
